package com.molan.molan_music.service.impl;

import com.molan.molan_music.dao.MusicDao;
import com.molan.molan_music.dto.MusicCreateRequest;
import com.molan.molan_music.dto.MusicDto;
import com.molan.molan_music.dto.MusicUpdateRequest;
import com.molan.molan_music.entity.Music;
import com.molan.molan_music.enums.MusicStatus;
import com.molan.molan_music.exception.BizException;
import com.molan.molan_music.exception.ExceptionType;
import com.molan.molan_music.mapper.MusicMapper;
import com.molan.molan_music.service.MusicService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MusicServiceImpl implements MusicService {

    @Resource
    private MusicMapper musicMapper;

    @Resource
    private MusicDao musicDao;

    @Override
    public MusicDto create(MusicCreateRequest musicCreateRequest) {
        Music music = musicMapper.createEntity(musicCreateRequest);
        music.setStatus(MusicStatus.DRAFT);
        music.setCreateTime((int) (System.currentTimeMillis()/1000));
        music.setUpdateTime((int) (System.currentTimeMillis()/1000));
        int insert = musicDao.insert(music, null);

        if(insert>0){
            Integer musicId = music.getMusicId();
            Music byId = musicDao.getById(musicId,null);
            return musicMapper.toDto(byId);
        }else {
            return null;
        }

    }

    @Override
    public MusicDto update(Integer id, MusicUpdateRequest musicUpdateRequest) {
        Music byId1 = musicDao.getById(id,null);
        if(Objects.isNull(byId1)){
            throw new BizException(ExceptionType.MUSIC_NOT_FOUND);
        }
        Music music = musicMapper.updateEntity(musicUpdateRequest);
        music.setMusicId(id);
        music.setUpdateTime((int) (System.currentTimeMillis()/1000));
        int update = musicDao.update(music, true, null);
        if(update>0){
            Integer musicId = music.getMusicId();
            Music byId = musicDao.getById(musicId,null);
            return musicMapper.toDto(byId);
        }else {
            return null;
        }

    }

    @Override
    public List<MusicDto> list(int pageNum,int pageSize) {
        List<Music> music = musicDao.listByEntity(new Music(), pageNum, pageSize, null, null);
        List<MusicDto> collect = music.stream().map(musicMapper::toDto).collect(Collectors.toList());

        return collect;
    }

}
